package com.ruoyi.charge.auth.controller;

import com.ruoyi.charge.auth.entity.req.LoginBody;
import com.ruoyi.charge.auth.entity.req.RefreshAccessTokenReq;
import com.ruoyi.charge.auth.entity.req.RegisterReq;
import com.ruoyi.charge.auth.entity.res.AccessTokenResponse;
import com.ruoyi.charge.auth.entity.res.RefreshTokenResponse;

import com.ruoyi.charge.service.IUserService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author fanqie
 * @date 2021-06-04
 */
@Api(value = "用户登陆", tags = {"用户登陆"})
@RestController
@RequestMapping("/charge/auth")
public class AuthController {


    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IUserService iUserService;


    /**
     * 登录
     *
     * @return 返回token
     */
    @ApiOperation("登录（返回token）")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Valid LoginBody loginBody) {
        AccessTokenResponse data = iUserService.getAccessTokenByAccount(loginBody.getPhone(), loginBody.getPassword());
        return AjaxResult.success(data);
    }


    @ApiOperation("刷新token")
    @PostMapping("/refresh/token")
    public AjaxResult refreshAccessToken(@RequestBody @Valid RefreshAccessTokenReq req) {
        RefreshTokenResponse data = iUserService.refreshAccessToken(req.getUserId(), req.getRefreshToken(), req.getType());
        return AjaxResult.success(data);
    }

    @ApiOperation("注册用户")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Valid RegisterReq req) {

        Boolean result = iUserService.register(req);
        if (result) {
            return AjaxResult.success();
        }
        return AjaxResult.error("手机号已注册！");
    }
}
